using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;

using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 章节重写服务
    /// </summary>
    public class ChapterRewriteService
    {
        private readonly IAIService _aiService;
        private readonly ILogger<ChapterRewriteService> _logger;
        private readonly string _configDirectory;

        public ChapterRewriteService(IAIService aiService, ILogger<ChapterRewriteService> logger)
        {
            _aiService = aiService;
            _logger = logger;
            _configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                "DocumentCreationSystem", "ChapterRewrite");
            
            // 确保配置目录存在
            Directory.CreateDirectory(_configDirectory);
        }

        /// <summary>
        /// 开始章节重写
        /// </summary>
        public async Task<bool> StartRewriteAsync(ChapterRewriteConfig config, 
            IProgress<(int progress, string message)>? progress = null,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始重写第{config.ChapterNumber}章");
                
                // 保存配置
                await SaveConfigAsync(config);
                
                // 备份原始文件
                if (config.BackupOriginal)
                {
                    await BackupOriginalFileAsync(config);
                }

                // 构建重写上下文
                var context = await BuildRewriteContextAsync(config);
                
                // 读取章节细纲
                var chapterOutline = await GetChapterOutlineAsync(config);
                
                config.UpdateStatus(ChapterRewriteStatus.InProgress, null, 10);
                await SaveConfigAsync(config);
                progress?.Report((10, "正在生成章节内容..."));

                // 生成新的章节内容
                var newContent = await GenerateChapterContentAsync(chapterOutline, context, config, progress, cancellationToken);
                
                if (string.IsNullOrEmpty(newContent))
                {
                    config.UpdateStatus(ChapterRewriteStatus.Failed, "生成的章节内容为空");
                    await SaveConfigAsync(config);
                    return false;
                }

                config.GeneratedContentLength = newContent.Length;
                config.UpdateStatus(ChapterRewriteStatus.InProgress, null, 90);
                await SaveConfigAsync(config);
                progress?.Report((90, "正在保存章节内容..."));

                // 保存新内容
                if (config.AutoSave)
                {
                    await File.WriteAllTextAsync(config.ChapterFilePath, newContent, Encoding.UTF8, cancellationToken);
                }

                config.UpdateStatus(ChapterRewriteStatus.Completed, null, 100);
                await SaveConfigAsync(config);
                progress?.Report((100, "章节重写完成"));

                _logger.LogInformation($"第{config.ChapterNumber}章重写完成");
                return true;
            }
            catch (OperationCanceledException)
            {
                config.UpdateStatus(ChapterRewriteStatus.Cancelled, "用户取消操作");
                await SaveConfigAsync(config);
                _logger.LogInformation($"第{config.ChapterNumber}章重写被取消");
                return false;
            }
            catch (Exception ex)
            {
                config.UpdateStatus(ChapterRewriteStatus.Failed, ex.Message);
                await SaveConfigAsync(config);
                _logger.LogError(ex, $"重写第{config.ChapterNumber}章时发生错误");
                return false;
            }
        }

        /// <summary>
        /// 续写章节（从中断点继续）
        /// </summary>
        public async Task<bool> ResumeRewriteAsync(ChapterRewriteConfig config,
            IProgress<(int progress, string message)>? progress = null,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"续写第{config.ChapterNumber}章，从{config.Progress}%继续");
                
                if (config.Status == ChapterRewriteStatus.Completed)
                {
                    _logger.LogWarning("章节已完成，无需续写");
                    return true;
                }

                // 检查是否有临时保存的内容
                string existingContent = "";
                if (!string.IsNullOrEmpty(config.TempSavePath) && File.Exists(config.TempSavePath))
                {
                    existingContent = await File.ReadAllTextAsync(config.TempSavePath, cancellationToken);
                }

                // 构建续写上下文
                var context = await BuildRewriteContextAsync(config);
                var chapterOutline = await GetChapterOutlineAsync(config);

                config.UpdateStatus(ChapterRewriteStatus.InProgress, null, Math.Max(config.Progress, 10));
                await SaveConfigAsync(config);
                progress?.Report((config.Progress, "正在续写章节内容..."));

                // 续写内容
                var newContent = await ContinueGenerateContentAsync(chapterOutline, context, existingContent, config, progress, cancellationToken);
                
                if (string.IsNullOrEmpty(newContent))
                {
                    config.UpdateStatus(ChapterRewriteStatus.Failed, "续写的章节内容为空");
                    await SaveConfigAsync(config);
                    return false;
                }

                config.GeneratedContentLength = newContent.Length;
                config.UpdateStatus(ChapterRewriteStatus.InProgress, null, 90);
                await SaveConfigAsync(config);
                progress?.Report((90, "正在保存章节内容..."));

                // 保存最终内容
                if (config.AutoSave)
                {
                    await File.WriteAllTextAsync(config.ChapterFilePath, newContent, Encoding.UTF8, cancellationToken);
                }

                config.UpdateStatus(ChapterRewriteStatus.Completed, null, 100);
                await SaveConfigAsync(config);
                progress?.Report((100, "章节续写完成"));

                _logger.LogInformation($"第{config.ChapterNumber}章续写完成");
                return true;
            }
            catch (Exception ex)
            {
                config.UpdateStatus(ChapterRewriteStatus.Failed, ex.Message);
                await SaveConfigAsync(config);
                _logger.LogError(ex, $"续写第{config.ChapterNumber}章时发生错误");
                return false;
            }
        }

        /// <summary>
        /// 构建重写上下文
        /// </summary>
        private async Task<string> BuildRewriteContextAsync(ChapterRewriteConfig config)
        {
            var context = new List<string>();

            foreach (var filePath in config.ReferenceFilePaths)
            {
                try
                {
                    if (File.Exists(filePath))
                    {
                        var content = await File.ReadAllTextAsync(filePath);
                        
                        // 限制单个文件的内容长度
                        var maxLength = config.MaxContextLength / Math.Max(config.ReferenceFilePaths.Count, 1);
                        if (content.Length > maxLength)
                        {
                            content = content.Substring(0, maxLength) + "...[内容已截断]";
                        }

                        var fileName = Path.GetFileName(filePath);
                        context.Add($"参考文件 [{fileName}]：\n{content}");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, $"读取参考文件失败: {filePath}");
                }
            }

            return string.Join("\n\n", context);
        }

        /// <summary>
        /// 获取章节细纲
        /// </summary>
        private async Task<string> GetChapterOutlineAsync(ChapterRewriteConfig config)
        {
            // 查找章节细纲文件
            var outlineFile = Path.Combine(config.ProjectPath, "大纲", "章节", $"第{config.ChapterNumber}章_细纲.txt");
            
            if (File.Exists(outlineFile))
            {
                return await File.ReadAllTextAsync(outlineFile);
            }

            // 如果没有找到细纲文件，返回默认提示
            return $"第{config.ChapterNumber}章细纲（请根据前文内容和参考资料创作本章内容）";
        }

        /// <summary>
        /// 生成章节内容
        /// </summary>
        private async Task<string> GenerateChapterContentAsync(string outline, string context, ChapterRewriteConfig config,
            IProgress<(int progress, string message)>? progress, CancellationToken cancellationToken)
        {
            var prompt = BuildRewritePrompt(outline, context, config);
            
            // 分段生成，支持进度报告
            var targetLength = config.TargetContentLength;
            var segmentLength = 1000; // 每段1000字
            var segments = (targetLength + segmentLength - 1) / segmentLength;
            
            var fullContent = new StringBuilder();
            
            for (int i = 0; i < segments; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                
                var segmentPrompt = i == 0 ? prompt : 
                    $"继续创作以下章节内容，保持风格一致：\n\n已有内容：\n{fullContent}\n\n请继续创作约{segmentLength}字：";
                
                var segmentContent = await _aiService.GenerateTextAsync(segmentPrompt, segmentLength);
                fullContent.AppendLine(segmentContent);
                
                var currentProgress = 10 + (80 * (i + 1) / segments);
                config.UpdateStatus(ChapterRewriteStatus.InProgress, null, currentProgress);
                await SaveConfigAsync(config);
                progress?.Report((currentProgress, $"正在生成第{i + 1}/{segments}段内容..."));
                
                // 保存临时内容（用于断点续写）
                if (config.EnableResume)
                {
                    await SaveTempContentAsync(config, fullContent.ToString());
                }
            }
            
            return fullContent.ToString();
        }

        /// <summary>
        /// 续写内容生成
        /// </summary>
        private async Task<string> ContinueGenerateContentAsync(string outline, string context, string existingContent,
            ChapterRewriteConfig config, IProgress<(int progress, string message)>? progress, CancellationToken cancellationToken)
        {
            var prompt = $"基于以下大纲和参考资料，继续完成章节内容：\n\n章节大纲：\n{outline}\n\n参考资料：\n{context}\n\n已有内容：\n{existingContent}\n\n请继续创作，完成整章内容：";
            
            var remainingLength = Math.Max(config.TargetContentLength - existingContent.Length, 500);
            var newContent = await _aiService.GenerateTextAsync(prompt, remainingLength);
            
            return existingContent + "\n" + newContent;
        }

        /// <summary>
        /// 构建重写提示词
        /// </summary>
        private string BuildRewritePrompt(string outline, string context, ChapterRewriteConfig config)
        {
            var styleInstruction = config.RewriteStyle switch
            {
                "优化表达" => "请优化语言表达，使文字更加流畅生动",
                "增强细节" => "请增加细节描写，丰富场景和人物刻画",
                "紧凑叙述" => "请采用紧凑的叙述风格，突出情节推进",
                _ => "请保持原有的写作风格"
            };

            return $@"请基于以下章节大纲和参考资料重写章节内容：

章节大纲：
{outline}

参考资料：
{context}

重写要求：
1. {styleInstruction}
2. 目标字数约{config.TargetContentLength}字
3. 保持故事连贯性和角色一致性
4. 采用小说的标准格式，包含对话、描写、心理活动等
5. 确保内容符合章节大纲的要求

请开始创作：";
        }

        /// <summary>
        /// 备份原始文件
        /// </summary>
        private async Task BackupOriginalFileAsync(ChapterRewriteConfig config)
        {
            if (File.Exists(config.ChapterFilePath))
            {
                var backupPath = config.ChapterFilePath + $".backup_{DateTime.Now:yyyyMMdd_HHmmss}";
                File.Copy(config.ChapterFilePath, backupPath);
                config.BackupFilePath = backupPath;
                _logger.LogInformation($"已备份原始文件到: {backupPath}");
            }
        }

        /// <summary>
        /// 保存临时内容
        /// </summary>
        private async Task SaveTempContentAsync(ChapterRewriteConfig config, string content)
        {
            if (string.IsNullOrEmpty(config.TempSavePath))
            {
                config.TempSavePath = Path.Combine(_configDirectory, $"temp_chapter_{config.ChapterNumber}_{DateTime.Now:yyyyMMdd_HHmmss}.txt");
            }
            
            await File.WriteAllTextAsync(config.TempSavePath, content, Encoding.UTF8);
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private async Task SaveConfigAsync(ChapterRewriteConfig config)
        {
            var configPath = Path.Combine(_configDirectory, $"rewrite_config_{config.ChapterNumber}.json");
            await File.WriteAllTextAsync(configPath, config.ToJson(), Encoding.UTF8);
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        public async Task<ChapterRewriteConfig?> LoadConfigAsync(int chapterNumber)
        {
            var configPath = Path.Combine(_configDirectory, $"rewrite_config_{chapterNumber}.json");
            
            if (File.Exists(configPath))
            {
                var json = await File.ReadAllTextAsync(configPath);
                return ChapterRewriteConfig.FromJson(json);
            }
            
            return null;
        }

        /// <summary>
        /// 检查是否有未完成的重写任务
        /// </summary>
        public async Task<List<ChapterRewriteConfig>> GetIncompleteTasksAsync()
        {
            var incompleteTasks = new List<ChapterRewriteConfig>();
            
            if (!Directory.Exists(_configDirectory))
                return incompleteTasks;
            
            var configFiles = Directory.GetFiles(_configDirectory, "rewrite_config_*.json");
            
            foreach (var configFile in configFiles)
            {
                try
                {
                    var json = await File.ReadAllTextAsync(configFile);
                    var config = ChapterRewriteConfig.FromJson(json);
                    
                    if (config != null && config.Status == ChapterRewriteStatus.InProgress)
                    {
                        incompleteTasks.Add(config);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, $"读取配置文件失败: {configFile}");
                }
            }
            
            return incompleteTasks;
        }
    }
}
